package com.csproj.basic.service;

import com.csproj.basic.domain.CollarRecord;
import com.csproj.basic.repository.CollarRecordRepository;
import com.csproj.basic.service.dto.CollarRecordDTO;
import com.csproj.basic.service.mapper.CollarRecordMapper;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.exception.BaseAppException;
import com.csproj.siiat.base.common.util.FileUtils;
import com.csproj.siiat.security.SecurityUtils;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.repository.UserInfoRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing CollarRecord.
 */
@Service
@Transactional
public class CollarRecordService {

    private final Logger log = LoggerFactory.getLogger(CollarRecordService.class);

    private final CollarRecordRepository collarRecordRepository;

    private final CollarRecordMapper collarRecordMapper;

    private final UserInfoRepository userInfoRepository;

    public CollarRecordService(CollarRecordRepository collarRecordRepository, CollarRecordMapper collarRecordMapper, UserInfoRepository userInfoRepository) {
        this.collarRecordRepository = collarRecordRepository;
        this.collarRecordMapper = collarRecordMapper;
        this.userInfoRepository = userInfoRepository;
    }

    /**
     * 保存领用记录并且返回前端需要发的dto，包括扩展属性createName
     * @param collarRecordDTO
     * @return containerDTO
     * TODO 主要负责从前端接收值
     * TODO DTO的扩展属性，在此方法复制
     */
    public CollarRecordDTO saveAndGetDTO(CollarRecordDTO collarRecordDTO) {
        CollarRecord collarRecord = collarRecordMapper.toEntity(collarRecordDTO);
        collarRecord = save(collarRecord);
        collarRecordDTO = collarRecordMapper.toDto(collarRecord);
        return collarRecordDTO;
    }

    /**
     * 保存领用记录
     * @param collarRecord
     * @return collarRecord
     * TODO 纯粹的保存方法，通用于所有保存业务调用
     * TODO 赋默认值，保存后，检查数据库，是否所有字段都有准确值
     */
    public CollarRecord save(CollarRecord collarRecord) {

        collarRecord.setCreationTime(ZonedDateTime.now());
        collarRecord.setCreatorUserId(SecurityUtils.getCurrentUserId());
        collarRecord.setDeletedFlag(false);
        return collarRecordRepository.save(collarRecord);
    }

    /**
     * 修改领用记录并且返回前端需要发的dto，包括扩展属性
     * @param collarRecordDTO
     * @return collarRecordDTO
     * TODO 类似SAVE
     */
    public CollarRecordDTO updateAndGetDTO(CollarRecordDTO collarRecordDTO) {
        CollarRecord collarRecord = collarRecordRepository.findOne(collarRecordDTO.getId());
        if(collarRecord == null){
            throw new BaseAppException(BaseDTO.CODE_PARAM,"id不存在");
        }
        collarRecord.setReceiveDate(collarRecordDTO.getReceiveDate());
        collarRecord.setReceiverId(collarRecordDTO.getReceiverId());
        collarRecord.setBackDate(collarRecordDTO.getBackDate());
        collarRecord = update(collarRecord);
        return collarRecordMapper.toDto(collarRecord);
    }

    /**
     * 修改领用记录
     * @param collarRecord
     * @return collarRecord
     * TODO 类似SAVE
     */
    public CollarRecord update(CollarRecord collarRecord) {
        CollarRecord collarRecordDB = findOne(collarRecord.getId());
        collarRecordDB.setLastModificationTime(ZonedDateTime.now());
        collarRecordDB.setLastModifierUserId(SecurityUtils.getCurrentUserId());

        collarRecordDB = collarRecordRepository.save(collarRecordDB);
        return collarRecordDB;
    }




    /**
     * TODO 返回纯粹的数据库对象，不包含扩展属性，适用于所有调取业务方法
     *
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public List<CollarRecord> findAll() {
        log.debug("Request to get all Containers");
        List<CollarRecord> collarRecords = collarRecordRepository.findAll();
        return collarRecords;
    }

    /**
     *  获取所有领用记录信息
     *  @return
     *  TODO 返回DTO，包含扩展属性
     *  TODO 如果扩展属性不同，可写多个findAllAndGetDTO1、findAllAndGetDTO2，注明扩展的属性
     */
    @Transactional(readOnly = true)
    public List<CollarRecordDTO> findAllAndGetDTO() {
        List<CollarRecordDTO> collarRecordDTOS = collarRecordMapper.toDto(findAll());
        return collarRecordDTOS;
    }

    /**
     * 根据id，获取领用记录信息
     *  @param id the id of the entity
     *  @return the entity
     *
     *  TODO 返回纯粹的数据库对象，不包含扩展属性，适用于所有调取业务方法
     */
    @Transactional(readOnly = true)
    public CollarRecord findOne(String id) {
        CollarRecord collarRecord = collarRecordRepository.findOne(id);
        if(collarRecord == null){
            throw new BaseAppException(BaseDTO.CODE_PARAM,"id_errors");
        }
        return collarRecord;
    }


    /**
     *  获取所有领用记录信息（分页）
     *  @return the list of entities
     *
     *  TODO 返回纯粹的数据库对象，不包含扩展属性，适用于所有调取业务方法
     */
    @Transactional(readOnly = true)
    public Page<CollarRecord> findPageList(Map<String, Object> map, Pageable pageable) {
        Page<CollarRecord> result = collarRecordRepository.findPageList(map,pageable);
        return result;
    }

    /**
     *  获取所有领用记录信息（分页）
     *  @return the list of entities
     *
     *  TODO 返回DTO，包含扩展属性
     *  TODO 如果扩展属性不同，findPageListAndGetDTO1、findPageListAndGetDTO2，注明扩展的属性
     */
    @Transactional(readOnly = true)
    public BaseDTO findPageListAndGetDTO(Map<String,Object> map, Pageable pageable) {
        Page<CollarRecord> result = findPageList(map,pageable);
        List<CollarRecord> containers = result.getContent();
        List<CollarRecordDTO> containerDTOS = collarRecordMapper.toDto(containers);
        //extendCompanyName(containerDTOS);
        return BaseDTO.createBaseDTO(result).setFieldList(containerDTOS);
    }


    /**
     * 根据设备ID查询舍用记录
     * @param deviceId  设备ID
     * @param map
     * @return
     */

    @Transactional(readOnly = true)
    public BaseDTO findPageListByDeviceId(String deviceId,Map<String,Object> map,Pageable pageable){
        map.put("deviceId",deviceId);
        Page<CollarRecord> result = collarRecordRepository.findPageListByDeviceId(map,pageable);
        List<CollarRecord> collarRecords = result.getContent();
        List<CollarRecordDTO> collarRecordDTOS = collarRecordMapper.toDto(collarRecords);
        extendsUserName(collarRecordDTOS);
        return BaseDTO.createBaseDTO(result).setFieldList(collarRecordDTOS);

    }


    /**
     *  根据接受人ID赋值 姓名
     */
    private void extendsUserName(List<CollarRecordDTO> collarRecordDTOS){

        List<String> userInfoIds = collarRecordDTOS.stream().map(collarRecordDTO -> collarRecordDTO.getReceiverId()).collect(Collectors.toList());
        if(userInfoIds.size()>0){
            List<UserInfo> userInfos = userInfoRepository.findByIds(userInfoIds.toArray(new String[userInfoIds.size()]));
            collarRecordDTOS.forEach(collarRecordDTO -> {
                UserInfo userInfo = userInfos.stream().filter(u->u.getId().equals(collarRecordDTO.getReceiverId())).findFirst().orElse(new UserInfo());
                collarRecordDTO.setReceiverName(userInfo.getAccount());
            });
        }

    }

    private void extendUserName(CollarRecordDTO collarRecordDTO){
        if(StringUtils.isBlank(collarRecordDTO.getReceiverId())){
            return;
        }
        UserInfo userInfo = userInfoRepository.findOne(collarRecordDTO.getId());
        if(userInfo!=null){
            collarRecordDTO.setReceiverName(userInfo.getAccount());
        }
    }
    /**
     * 根据id，获取领用记录信息
     *  @param id 主键id
     *  @return creator、questionTypeName
     *
     *  TODO 返回DTO，包含扩展属性
     *  TODO 如果扩展属性不同，findPageListAndGetDTO1、findPageListAndGetDTO2，注明扩展的属性
     */
    @Transactional(readOnly = true)
    public CollarRecordDTO findOneAndGetDTO(String id) {
        CollarRecord collarRecord = findOne(id);
        CollarRecordDTO collarRecordDTO = collarRecordMapper.toDto(collarRecord);
        return collarRecordDTO;
    }

    /**
     *  根据id，删除领用记录信息
     *  @param id the id of the entity
     */
    public void delete(String id) {
        collarRecordRepository.delete(id);
    }

    /**
     * 根据机构ids，批量删除领用记录信息
     * @param ids
     */
    public void deleteIds(String[] ids){
        collarRecordRepository.deleteIds(ids);
    }

    /**
     * 上传文件
     * @param file
     */
    public String uploadFile(HttpServletRequest request, MultipartFile file){
        String filePath = FileUtils.excelUpload(request,file, File.separator+"upload"+ File.separator+"warehouse");
        return filePath;
    }

    /**
     * 根据deviceId查询记录
     * @param deviceId
     * @return
     */
    @Transactional(readOnly = true)
    public CollarRecordDTO findByDeviceId(String deviceId) {

        List<CollarRecord> collarRecords = collarRecordRepository.findByDeviceId(deviceId);
        CollarRecord collarRecord = new CollarRecord();
        if(collarRecords.size()>0){
            collarRecord = collarRecords.get(0);
        }

        CollarRecordDTO collarRecordDTO = collarRecordMapper.toDto(collarRecord);
        extendUserName(collarRecordDTO);
        return collarRecordDTO;

    }
}
